from app.extensions import SessionLocal
from app.models.Student import Student
from app.models.Clas import Clas

class StudentRepository:
    def __init__(self, db: SessionLocal):
        self.db = db

    def get_by_keyword(self, keyword):
        try:
            data = self.db.query(Student).filter(Student.id.like(f"%{keyword}%")).all()
            return data
        except:
            return []

    def get_student_by_id(self, id):
        try:
            data = self.db.query(Student).filter(Student.id == id).one()
            return data
        except:
            return None

    def get_clas_by_id(self,student_clas_id):
        try:
            return self.db.query(Clas).filter(Clas.id == student_clas_id).first()
        except:
            return None

    def add_student(self, student):
        try:
            self.db.add(student)
            self.db.commit()
            return True
        except Exception as e:
            self.db.rollback()
            print(f"数据库操作失败: {str(e)}")
            return False

    def modify_student(self, id, name, gender,clas_id):
        try:
            student = self.get_student_by_id(id)
            if not student:
                print(f"未找到学生学号: {id}")
                return False
            student.name = name
            student.gender = gender
            student.clas_id = clas_id
            self.db.commit()
            return True
        except Exception as e:
            self.db.rollback()
            print(f"更新学生失败: {e}")
            return False

    def delete_student(self, id):
        try:
            student = self.db.query(Student).filter_by(id=id).first()
            if not student:
                print(f"未找到学生学号：{id}")
                return False
            self.db.delete(student)
            self.db.commit()
            return True
        except Exception as e:
            self.db.rollback()
            print(f"删除学生失败: {e}")
            return False

if __name__ == '__main__':
    from app.extensions import get_db
    with get_db() as db:
        repo = StudentRepository(db)
        data = repo.get_by_keyword("")
        for d in data:
            print(d)